package com.jason.www.controller;

import com.jason.www.commons.PropertyConfigurer;
import com.jason.www.controller.vo.PayCallbackVo;
import com.jason.www.controller.vo.PayRequestVo;
import com.jason.www.service.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import static com.jason.www.enums.PayType.NEWALIPAY;

/**
 * 单独的支付宝支付
 */
@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    IPayService payService;
    @Autowired
    PropertyConfigurer propertyConfigurer;

    @RequestMapping(value = "/paymsg", method = RequestMethod.POST)
    public void paymsg(HttpServletRequest request, HttpServletResponse response, @RequestBody PayRequestVo payRequestVo) throws IOException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        payRequestVo.setRequestUrl(request.getRequestURL().toString().replace(request.getRequestURI(), ""));
        testData(payRequestVo);
        String form = payService.constructPayMessage(NEWALIPAY, BeanUtils.describe(payRequestVo));
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
    }


    /**
     * 构建测试订单数据
     * @param payRequestVo
     */
    private void testData(@RequestBody PayRequestVo payRequestVo) {
        payRequestVo.setRequestUrl(propertyConfigurer.getRequestUrl());
        payRequestVo.setOrderId("TEST" + LocalDateTime.now().toString());
        payRequestVo.setSubject("测试订单");
        payRequestVo.setTotalPrice("0.01");
        payRequestVo.setNotifyUrl(propertyConfigurer.getAlipayNotifyUrl());
    }

    @RequestMapping(value = "/alipay-notify", method = RequestMethod.POST)
    public void alipayNotify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        Map<String, String> params = getAllRequestParam(request, StandardCharsets.UTF_8.toString());
        log.info("支付宝回调的参数为====>" + params);

        if (payService.verifyCallbackHmac(NEWALIPAY, params)) {
            log.info("新版支付宝调用验证参数成功");
            String trade_status = params.get("trade_status");
            if (trade_status.equals("TRADE_FINISHED")) {
                log.info("支付宝回调返回：TRADE_FINISHED");
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                try {
                    log.info("支付宝回调返回：TRADE_SUCCESS");
                    PayCallbackVo vo = PayCallbackVo.buildAlipayCallback(params);
                    System.out.println(vo);
                } catch (Exception e) {
                    log.info("支付宝回调成功但是业务发生异常:", e);
                }
            }

        }
    }

    private static Map<String, String> getAllRequestParam(final HttpServletRequest request, String encoding) throws UnsupportedEncodingException {
        request.setCharacterEncoding(encoding);
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String key = (String) temp.nextElement();
                String value = request.getParameter(key);
                if (StringUtils.isNotEmpty(value)) {
                    res.put(key, value);
                }
            }
        }
        return res;
    }
}
